package com.qdsg.ysg.doctor.ui;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.shape.view.ShapeTextView;
import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseActivity;
import com.qdsg.ysg.doctor.base.BaseApplication;
import com.qdsg.ysg.doctor.eventbus.WebSocket;
import com.qdsg.ysg.doctor.util.ImageLoaderHelper;
import com.qdsg.ysg.doctor.util.UIConstants;
import com.qdsg.ysg.doctor.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.response.BaseResponse;
import com.rest.response.ChatResponse;
import com.rest.response.IMListResponse;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.UtilList;

/**
 * @author Administrator
 * @date 2018/5/28
 */

public class IMActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.cl_empty)
    ConstraintLayout clEmpty;
    MyAdapter adapter;
    String imFlag;
    List<IMListResponse.IMItem> list = new ArrayList<>();


    @Override
    protected int getLayoutResource() {
        return R.layout.aty_base_list;
    }

    @Override
    protected void initViews() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);

        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> queryIMList());
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {

        });
    }

    @Override
    protected void initData() {
        imFlag = getIntent().getStringExtra(UIConstants.IM_FLAG);
        EventBus.getDefault().register(this);
        if ("0".equals(imFlag)) {
            //待接诊
            tvTitle.setText(R.string.string_waiting_reception);
        } else {
            //进行中
            tvTitle.setText(R.string.string_in_progress);
        }
    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(IMActivity.this).inflate(R.layout.item_im, parent, false));
            return myHolder;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putSerializable("diagnoseId", list.get(position).diagnoseId);
                startActivity(ChatActivity.class, bundle);
            });
            holder.itemView.setOnLongClickListener(v -> {
                if (list.get(position).patientIsTop == 0) {
                    new AlertDialog.Builder(IMActivity.this).setTitle("置顶")
                            .setMessage("是否置顶该聊天")
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 显示授权界面
                                updateTop(list.get(position).diagnoseId, 1 + "");
                            })
                            .setNegativeButton("取消", null).show();
                } else {
                    new AlertDialog.Builder(IMActivity.this).setTitle("置顶")
                            .setMessage("是否取消置顶该聊天")
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 显示授权界面
                                updateTop(list.get(position).diagnoseId, 0 + "");
                            })
                            .setNegativeButton("取消", null).show();
                }
                return false;
            });
            holder.tv_name.setText(list.get(position).patientName);
            holder.tv_department.setText(list.get(position).sex + " " + list.get(position).age);
            if (list.get(position).businessType == UIConstants.GRAPHIC_TYPE_1) {
                holder.tv_consult_type.setText(R.string.string_consult);
//                holder.tv_consult_type.setBackgroundColor(getResources().getColor(R.color.color_orange));

            } else if (list.get(position).businessType == UIConstants.GRAPHIC_TYPE_2) {
                holder.tv_consult_type.setText(R.string.string_referral);
//                holder.tv_consult_type.setBackgroundColor(getResources().getColor(R.color.chooser_orange));
            }
            if ("0".equals(imFlag)) {
                holder.tv_message.setText("病情描述:" + list.get(position).oneselfState);
            } else if (list.get(position).messageType == ChatResponse.TEXT) {
                holder.tv_message.setText(list.get(position).content);
            } else if (list.get(position).messageType == ChatResponse.IMAGE) {
                holder.tv_message.setText("[图片]");
            } else if (list.get(position).messageType == -1) {
                holder.tv_message.setText("");
            } else if (list.get(position).messageType == ChatResponse.PRESCRIPTION) {
                holder.tv_message.setText("[处方]");
            } else if (list.get(position).messageType == ChatResponse.AUDIO) {
                holder.tv_message.setText("[语音]");
            } else if (list.get(position).messageType == ChatResponse.CHECKOUT) {
                holder.tv_message.setText("[检查检验]");
            }
            holder.tv_time.setText(list.get(position).sendTime);
            if (list.get(position).unreadCount != 0) {
                holder.tv_unreadCount.setVisibility(View.VISIBLE);
                holder.tv_unreadCount.setText(list.get(position).unreadCount + "");
            } else {
                holder.tv_unreadCount.setVisibility(View.GONE);
            }
            if (!UtilString.isEmpty(list.get(position).patientAvatar)) {
                //加载患者头像
                ImageLoaderHelper.getInstance().GlideCircleImageLoader(IMActivity.this, list.get(position).patientAvatar, holder.img_head);
            } else if ("女".equals(list.get(position).sex)) {
                holder.img_head.setImageDrawable(ContextCompat.getDrawable(IMActivity.this, R.mipmap.icon_girl));
            } else {
                holder.img_head.setImageDrawable(ContextCompat.getDrawable(IMActivity.this, R.mipmap.icon_boy));
            }

        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name, tv_department, tv_message, tv_time, tv_unreadCount;
            ShapeTextView tv_consult_type;
            ImageView img_head;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_unreadCount = itemView.findViewById(R.id.tv_unreadCount);
                tv_time = itemView.findViewById(R.id.tv_time);
                tv_department = itemView.findViewById(R.id.tv_department);
                tv_consult_type = itemView.findViewById(R.id.tv_consult_type);
                tv_message = itemView.findViewById(R.id.tv_message);
                img_head = itemView.findViewById(R.id.img_head);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void queryIMList() {
        if (BaseApplication.currentUserId == null) {
            return;
        }
        RestProxy.getInstance().queryIMList(BaseApplication.currentUserId, imFlag, new Observer<IMListResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(IMListResponse imListResponse) {
                if (!UtilList.isEmpty(imListResponse.data.records)) {
                    refreshLayout.setVisibility(View.VISIBLE);
                    clEmpty.setVisibility(View.GONE);
                    list.clear();
                    list.addAll(imListResponse.data.records);
                    adapter.notifyDataSetChanged();
                } else {
                    refreshLayout.setVisibility(View.GONE);
                    clEmpty.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void onError(Throwable e) {
                refreshLayout.finishRefresh(false);
            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        queryIMList();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WebSocket webSocket) {
        if (webSocket.eventFlag == 0) {
            queryIMList();
        }
    }

    private void updateTop(String diagnoseId, String status) {

        RestProxy.getInstance().updateTop(diagnoseId, status, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                queryIMList();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }
}
